
import { Component, OnInit, Input, Output, EventEmitter, OnChanges, ChangeDetectorRef } from '@angular/core';

import { ModalController, NavParams, Platform } from '@ionic/angular';

import { Camera } from '@ionic-native/camera/ngx';


import { ActionSheetController } from '@ionic/angular';


import { ImgPage } from './img.page';
import { UploadImageService } from 'src/app/shared/service/uploadImageService';

declare let cordova;
@Component({
    selector: 'app-upload-image',
    templateUrl: './upload-image.component.html',
    styleUrls: ['./upload-image.component.scss']
})
export class UploadImageComponent implements OnInit, OnChanges {
    // 图片上传组件： 用法<app-upload-image [(imgObj)]="img" [selectType]="'single'"></app-upload-image>
    constructor(

        private modalCtrl: ModalController,
        private camera: Camera,

        private platform: Platform,
        private navParams: NavParams,
        private ref: ChangeDetectorRef,
        // private webview: WebView,
        private actionSheetCtrl: ActionSheetController,

        private uploadImageService: UploadImageService

    ) {

    }
    loaderToShow: any;
    selectImg: any;    // 选择好的图片
    showImg: any;      // 显示的图片
    isNative = false;
    @Input()
    selectType: any;   // 父组件传过来的type,用于判定是单选还是多选
    @Input()
    imgObj: any;    // 父元素传过来的图片对象，用于编辑页面等，格式是 ["imgurl1","imgurl2"]
    @Output()
    imgObjChange: EventEmitter<any> = new EventEmitter();
    img: any; // 返回给postEditComponent页面的图片
    originalImg: any;
    imgCount = 10; // 限制只能选择几张图片 默认选择10张

    base64Image: string;

    imageResponse: any;
    isCompleteBatchUpload: number;
    ngOnChanges() {

    }

    ngOnInit() {
        console.log('进来了？');
        console.log(this.navParams.data);
        if (this.navParams.data.imgCount !== undefined) {
            this.imgCount = this.navParams.data.imgCount;
        }
        this.img = JSON.parse(this.navParams.data.value);
        if (this.img !== undefined && this.img.length > 0) {
            this.originalImg = this.img;
        }
        if (this.platform.is('cordova')) {
            this.isNative = true;
        } else {
            this.isNative = false;
        }
        // console.log(" message-----> 75 ngOnInit img = " + JSON.stringify(this.img));
        console.log(' message-----> 75 originalImg = ' + JSON.stringify(this.img));
    }
    // 关闭模态框并传参
    dismiss() {
        this.modalCtrl.dismiss(this.img);
    }
    dismissWithNoImg() {
        if (this.originalImg !== undefined && this.originalImg.length > 0) {
            this.img = this.originalImg;
        } else {
            this.img = [];
        }
        this.modalCtrl.dismiss(this.img);
    }

    uploadFile(event: any) {
        if (this.isNative) {
            // this.takePicture()
        } else {
            const that = this;
            // 2024.06.14 整合统一从uploadImageService处理
            if (event.target.files && event.target.files[0]) {
                this.selectImg = event.target.files[0];
                this.uploadImageService.uploadFileForWeb(this.selectImg, (url) => {
                    that.img.push({ name: that.selectImg.name, path: url });
                }, false);
            }
        }
    }

    async presentAction() {
        const that = this;
        const actionSheet = await this.actionSheetCtrl.create({
            mode: 'ios',
            cssClass: 'as_padding as_common as_border_common',
            buttons: [{
                text: '相机',
                cssClass: 'as_font_bd',
                handler: () => {
                    const source = this.camera.PictureSourceType.CAMERA;
                    // 2024.06.14 整合统一从uploadImageService处理
                    this.uploadImageService.takePicture(source, false, (url, fileName) => {
                        const newEntry = {
                            name: fileName ? fileName : new Date() + '',
                            path: url
                        };
                        that.img.push(newEntry);
                    }, null);
                }
            }, {
                text: '从手机相册选择',
                cssClass: 'as_font_color',
                handler: () => {
   
                    // 2024.06.14 整合统一从uploadImageService处理
                    this.uploadImageService.openImgPicker((url, fileName) => {
                        // 2024.06.14  回调函数中处理各自的具体业务
                        const newEntry = {
                            name: fileName,
                            path: url
                        };
                        console.log(' message-----> 255 upload img  success ');
                        that.img.push(newEntry);
                    }, 1, this.isCompleteBatchUpload, null, false, this.ref);
                }
            },
            {
                text: '取消',
                cssClass: 'as_font_top',
                handler: () => {
                }
            }]
        });
        await actionSheet.present();
    }
    // 打开图片展示框，滑动展示
    async openImg(pos) {
        console.log(' message-----> 273 upload pos[' + (pos) + '] ');
        const that = this;
        const modal = await this.modalCtrl.create({
            component: ImgPage,
            componentProps: { value: JSON.stringify(this.img), index: pos }
        });
        modal.onDidDismiss().then((data) => {
            that.img = data.data;
        });
        return await modal.present();
    }


}
